<template>
  <div class="flex flex-col h-full">

    <!-- 上部分 -->
    <div class="flex mb-4">
      <SystemStatusChart :chart-data="statusData" class="w-2/5" />
      <StatisticsCards :statistics-data="statisticsData" class="w-3/5" />
    </div>

    <!-- 下部分 -->
    <div class="flex-1 flex flex-col min-h-0">
      <PageState :loading="loading" :error-message="errorMessage" :has-data="true" @retry="reload">
        <SystemTable :table-data="tableData" :pagination="pagination" @page-change="handlePageChange" />
      </PageState>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from "vue";
import SystemStatusChart from "./components/SystemStatusChart.vue";
import StatisticsCards from "./components/StatisticsCards.vue";
import SystemTable from "./components/SystemTable.vue";
import { getSystemStatus, getSystemStatistics, getSystemList } from "./data";
import PageState from "@/components/base/PageState.vue";
import { getCurrentTime, getTimezoneDisplayName } from "@/utils/timezone";
defineOptions({
  name: "SystemOverview"
});

// 顶部图表与卡片：从真实 API 获取
const statusData = ref({ normal: 0, faulty: 0, offline: 0, standby: 0 });
const statisticsData = ref<any>({
  updateTime: "",
  solar: { totalGeneration: 0 },
  home: { consumption: 0 },
  grid: { export: 0, import: 0 },
  battery: { energyCharged: 0, energyDischarged: 0 }
});

// 底部表格
const tableData = ref<any[]>([]);
const pagination = ref({ total: 0, currentPage: 1, pageSize: 10 });

const handlePageChange = async (page: number) => {
  pagination.value.currentPage = page;
  await loadAccounts();
};

const loadTopCards = async () => {
  const [statusRes, statRes] = await Promise.all([
    getSystemStatus(),
    getSystemStatistics()
  ]);
  if (statusRes.success && statusRes.data) {
    const s = statusRes.data as any;
    statusData.value = {
      normal: Number(s.normalCount) || 0,
      faulty: Number(s.faultCount) || 0,
      offline: Number(s.offlineCount) || 0,
      standby: Number(s.standbyCount) || 0
    };
  }
  if (statRes.success && statRes.data) {
    const d: any = statRes.data; // data.systemStatistics
    statisticsData.value = {
      updateTime: '', // 不再使用后端时间，前端自己显示当前时间
      solar: { totalGeneration: d?.solar?.totalGeneration || 0 },
      home: { consumption: d?.home?.consumption || 0 },
      grid: { export: d?.grid?.export || 0, import: d?.grid?.import || 0 },
      battery: { energyCharged: d?.battery?.energyCharged || 0, energyDischarged: d?.battery?.energyDischarged || 0 }
    };
  }
};

const loadAccounts = async () => {
  loading.value = true;
  errorMessage.value = "";
  const { list, totalCount } = await getSystemList({
    page: pagination.value.currentPage,
    limit: pagination.value.pageSize
  });
  tableData.value = (list || []).map((it: any) => ({
    id: it.systemId || it.id || '-',
    status: it.status,
    name: it.systemName || it.name || '-',
    region: it.country || it.countryRegion || '-',
    address: it.address || '-',
    lastUpdateTime: it.lastUpdateTime || it.updateTime || it.modifyTime || it.createTime || new Date().toISOString(),
    // 透传真实标识，供详情页使用
    hemsId: it.hemsId,
    deviceKey: it.deviceKey
  }));
  // console.log('[SYS] overview table first row:', tableData.value[0]);
  pagination.value.total = totalCount;
  loading.value = false;
};

onMounted(async () => {
  await Promise.all([loadTopCards(), loadAccounts()]);
});

// 时区相关
const currentTime = ref(getCurrentTime());
const timezoneDisplayName = ref(getTimezoneDisplayName());
let timeUpdateInterval: number | null = null;

// 状态
const loading = ref(false);
const errorMessage = ref("");
const reload = async () => {
  errorMessage.value = "";
  await loadAccounts();
};

// 更新时间显示
const updateTime = () => {
  currentTime.value = getCurrentTime();
};

onMounted(() => {
  // 每秒更新时间显示
  timeUpdateInterval = setInterval(updateTime, 1000);
});

onUnmounted(() => {
  if (timeUpdateInterval) {
    clearInterval(timeUpdateInterval);
  }
});
</script>
